package com.bwf.lgqingdan.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/20.
 */

public class SearchHistoryHandler extends QingdanDbHelper{
    private SQLiteDatabase db;
    public SearchHistoryHandler(Context context) {
        super(context);
        db = getReadableDatabase();
    }

    /**
     * 添加一条搜索关键字
     * 如果之前已经被添加，就修改这条记录的时间
     * @param keyword
     */
    public void addKeyword(String keyword){
        if(TextUtils.isEmpty(keyword)){
            return;
        }
        if(!existKeyword(keyword)){
            ContentValues values = new ContentValues();
            values.put(TableSearchHistoryColumns.KEYWORD,keyword);
            values.put(TableSearchHistoryColumns.TIME,System.currentTimeMillis());
            db.insert(TableSearchHistoryColumns.TAB_NAME,null,values);
        }else{
            ContentValues values = new ContentValues();
            values.put(TableSearchHistoryColumns.TIME,System.currentTimeMillis());
            String whereClause = TableSearchHistoryColumns.KEYWORD + " = ?";
            String[] whereArgs = {keyword};
            db.update(TableSearchHistoryColumns.TAB_NAME,values,whereClause,whereArgs);
        }
    }

    /**
     * 判断表中是否存在某搜索关键字记录
     * @param keyword
     * @return
     */
    private boolean existKeyword(String keyword) {
        String selection = TableSearchHistoryColumns.KEYWORD + " = ?";
        String[] selectionArgs = {keyword};
        Cursor cursor = db.query(TableSearchHistoryColumns.TAB_NAME,null,selection,selectionArgs,null,null,TableSearchHistoryColumns.TIME +" desc");
        boolean exist = cursor.getCount() != 0;
        cursor.close();
        return exist;
    }

    /**
     * 按照时间倒序查询
     * @return
     */
    public List<String> queryByTimeDesc(){
        String[] columns = {TableSearchHistoryColumns.KEYWORD};
        Cursor cursor = db.query(TableSearchHistoryColumns.TAB_NAME,columns,null,null,null,null,TableSearchHistoryColumns.TIME +" desc");
        if(cursor.getCount() == 0){
            cursor.close();
            return null;
        }
        List<String> list = new ArrayList<>();
        while (cursor.moveToNext()){
            list.add(cursor.getString(cursor.getColumnIndex(TableSearchHistoryColumns.KEYWORD)));
        }
        cursor.close();
        return list;
    }

    /**
     * 关闭数据库
     */
    public void closeDB(){
        if(db != null){
            db.close();
        }
    }

    /**
     * 清空表中所有数据
     */
    public void clearAllDecords(){
        db.delete(TableSearchHistoryColumns.TAB_NAME,null,null);
    }
}
